package com.lzw.controller;

import com.alibaba.fastjson.JSONObject;
import com.lzw.bean.base.TblUserRecord;
import com.lzw.resultjson.Permission;
import com.lzw.resultjson.Permissions;
import com.lzw.resultjson.ResultObject;
import com.lzw.resultjson.UserInfo;
import com.lzw.service.base.TblUserRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther: lzw
 * @date: 2021/11/16 - 11 - 16 - 17:06
 * @Description: com.lzw.controller
 */

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private TblUserRecordService tblUserRecordService;

    @RequestMapping("/auth/2step-code")
    public void step(){
        System.out.println("什么也不干");
    }

    @RequestMapping("/auth/login")
    public JSONObject login(@RequestParam("username") String username, @RequestParam String password
            , HttpSession session){
        log.info(username+"----"+password);
        TblUserRecord tblUserRecord = tblUserRecordService.login(username, password);
        tblUserRecord.setToken(tblUserRecord.getUserName());
        log.info(tblUserRecord.toString());
        session.setAttribute("userRecord", tblUserRecord);
        ResultObject resultObject = new ResultObject("success", tblUserRecord);
        return JSONObject.parseObject(JSONObject.toJSONString(resultObject));
    }

    @RequestMapping("/user/info")
    public JSONObject userInfo(HttpSession session){
        TblUserRecord userRecord = (TblUserRecord) session.getAttribute("userRecord");
//        System.out.println("session中的record"+userRecord);
        String[] roleprivileges = userRecord.getTblRole().getRolePrivileges().split("-");
        Permissions permissions = new Permissions();
        List<Permission> permissionList = new ArrayList<>();
        for (String roleprivilege : roleprivileges) {
            permissionList.add(new Permission(roleprivilege));
        }
        permissions.setPermissions(permissionList);
        UserInfo userInfo = new UserInfo(userRecord.getUserName(), permissions);
        ResultObject resultObject = new ResultObject("获取权限信息", userInfo);
        System.out.println(JSONObject.parseObject(JSONObject.toJSONString(resultObject)));
        return JSONObject.parseObject(JSONObject.toJSONString(resultObject));
    }

    @RequestMapping("/auth/logout")
    public JSONObject userLogout(HttpSession session){
        TblUserRecord userRecord = (TblUserRecord) session.getAttribute("userRecord");
        log.info(userRecord.getUserName()+"退出登录");
        session.invalidate();
        return JSONObject.parseObject(JSONObject.toJSONString(new ResultObject("",null)));
    }



}
